package com.shawn.autoconfig.template;

import com.baidu.aip.face.AipFace;
import com.shawn.autoconfig.properties.FaceIdProperties;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import java.util.HashMap;

/**
 * 面对id模板
 * 人脸识别模板
 *
 * @author lenovo
 * @date 2022/10/25
 */
@Slf4j
public class FaceIdTemplate {
    private FaceIdProperties faceIdProperties;

    public FaceIdTemplate(FaceIdProperties faceIdProperties) {
        this.faceIdProperties = faceIdProperties;
    }


    /**
     * 面检查
     *
     * @param imageURL 图像url
     * @return boolean
     */
    public boolean faceCheck(String imageURL) {
        //设置APPID/AK/SK
        String appId = faceIdProperties.getAppId();
        String apiKey = faceIdProperties.getApiKey();
        String secretKey = faceIdProperties.getSecretKey();

        AipFace client = new AipFace(appId, apiKey, secretKey);

        //设置网络连接参数 超时时间2秒
        client.setConnectionTimeoutInMillis(20000);
        //响应超时时间
        client.setSocketTimeoutInMillis(600000);

        String imageType = "URL";

        HashMap<String, String> options = new HashMap<>();
        options.put("face_field", "age");
        options.put("max_face_num", "2");
        options.put("face_type", "LIVE");
        options.put("liveness_control", "LOW");

        // 人脸检测
        log.info("开始人脸识别...");
        JSONObject res = client.detect(imageURL, imageType, options);
        Integer error_code = (Integer) res.get("error_code");
        boolean result = error_code == 0;
        if (result) {
            log.info("人脸检测成功!");
        } else {
            log.error("人脸检测失败!");
        }
        return result;
    }
}
